<template>
  <!-- 只有当浏览器支持屏幕录制功能时才显示组件 -->
  <div v-if="isSupported" class="screen-recorder-container" :class="{ expanded: isExpanded }">
    <div class="recorder-toggle" @click="toggleExpand">
      <video-camera-outlined />
      <span v-if="isExpanded">收起</span>
      <span v-if="!isExpanded">录制</span>
    </div>

    <div v-if="isExpanded" class="recorder-content">
      <div class="recorder-header">
        <h3>屏幕录制</h3>
      </div>

      <div class="recorder-controls">
        <div class="button-group">
          <a-button type="primary" :disabled="isRecording" @click="startRecording" :loading="isLoading">
            <template #icon><play-circle-outlined /></template>
            开始录制
          </a-button>
          <a-button danger :disabled="!isRecording" @click="stopRecording">
            <template #icon><stop-outlined /></template>
            停止录制
          </a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlayCircleOutlined, StopOutlined, VideoCameraOutlined } from '@ant-design/icons-vue'

// 状态变量
const isRecording = ref(false)
const isLoading = ref(false)
const recordedBlob = ref(null)
const mediaRecorder = ref(null)
const recordedChunks = ref([])
const stream = ref(null)
const isExpanded = ref(false)
const isSupported = ref(false) // 浏览器是否支持屏幕录制功能

// 切换展开/收起状态
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}

// 停止所有媒体轨道
const stopMediaTracks = () => {
  if (stream.value) {
    stream.value.getTracks().forEach((track) => track.stop())
    stream.value = null
  }
}

// 开始录制
const startRecording = async () => {
  isLoading.value = true
  recordedChunks.value = []

  try {
    // 获取屏幕媒体流
    stream.value = await navigator.mediaDevices.getDisplayMedia({
      video: {
        cursor: 'always'
      },
      audio: true
    })

    // 创建 MediaRecorder，使用 MP4 格式
    // 尝试使用 H.264 编码，这是苹果设备常用的编码格式
    let options = {}

    // 检查浏览器支持的 MIME 类型
    if (MediaRecorder.isTypeSupported('video/mp4;codecs=h264,aac')) {
      options = { mimeType: 'video/mp4;codecs=h264,aac' }
    } else if (MediaRecorder.isTypeSupported('video/mp4')) {
      options = { mimeType: 'video/mp4' }
    } else {
      // 回退到 WebM 格式，几乎所有支持 MediaRecorder 的浏览器都支持
      options = { mimeType: 'video/webm;codecs=vp9,opus' }
      console.warn('浏览器不支持 MP4 格式录制，将使用 WebM 格式')
    }

    mediaRecorder.value = new MediaRecorder(stream.value, options)

    // 设置事件处理
    mediaRecorder.value.ondataavailable = (event) => {
      if (event.data.size > 0) {
        recordedChunks.value.push(event.data)
      }
    }

    mediaRecorder.value.onstop = () => {
      const blob = new Blob(recordedChunks.value, { type: options.mimeType })
      recordedBlob.value = blob
      isRecording.value = false

      // 直接下载录制结果
      downloadVideo(blob)
    }

    // 开始录制
    mediaRecorder.value.start()
    isRecording.value = true
    message.success('开始录制')

    // 监听流结束事件
    stream.value.getVideoTracks()[0].onended = () => {
      if (isRecording.value) {
        stopRecording()
      }
    }
  } catch (error) {
    message.error('无法开始录制: ' + (error.message || '未知错误'))
  } finally {
    isLoading.value = false
  }
}

// 停止录制
const stopRecording = () => {
  if (mediaRecorder.value && isRecording.value) {
    mediaRecorder.value.stop()
    stopMediaTracks()
    message.success('录制已停止，正在下载视频...')
  }
}

// 下载录制的视频
const downloadVideo = (blob) => {
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.style.display = 'none'
  a.href = url

  // 根据实际使用的 MIME 类型设置文件扩展名
  const fileExtension = blob.type.includes('mp4') ? 'mp4' : 'webm'
  a.download = `screen-recording-${new Date().toISOString().slice(0, 19).replace(/:/g, '-')}.${fileExtension}`

  document.body.appendChild(a)
  a.click()
  setTimeout(() => {
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
  }, 100)

  // 下载完成后显示提示
  message.success(`视频已下载为 ${fileExtension.toUpperCase()} 格式`)
}

// 检查浏览器是否支持屏幕录制功能
const checkBrowserSupport = () => {
  // 检查基本的媒体设备支持
  if (!navigator.mediaDevices || !navigator.mediaDevices.getDisplayMedia) {
    return false
  }

  // 检查 MediaRecorder 支持
  if (!window.MediaRecorder) {
    return false
  }

  // 检查是否支持至少一种录制格式
  const supportedTypes = ['video/mp4;codecs=h264,aac', 'video/mp4', 'video/webm;codecs=vp9,opus', 'video/webm']

  return supportedTypes.some((type) => MediaRecorder.isTypeSupported(type))
}

// 组件挂载时
onMounted(() => {
  // 检查浏览器支持并设置状态
  isSupported.value = checkBrowserSupport()
})

// 组件卸载时
onUnmounted(() => {
  stopMediaTracks()
})
</script>

<style scoped>
.screen-recorder-container {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  background-color: #fff;
  border-radius: 8px 0 0 8px;
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
}

.recorder-toggle {
  padding: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #344767;
  border-radius: 8px 0 0 8px;
  transition: all 0.3s;
}

.recorder-toggle:hover {
  background-color: #f0f5ff;
}

.recorder-toggle span {
  margin-left: 8px;
}

.expanded {
  width: 240px;
  padding: 16px;
}

.recorder-content {
  margin-top: 12px;
}

.recorder-header {
  margin-bottom: 16px;
}

.recorder-header h3 {
  font-size: 16px;
  margin: 0;
}

.recorder-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.button-group {
  display: flex;
  gap: 8px;
}

/* 当录制中时，添加一个指示器 */
.expanded.recording .recorder-toggle {
  color: #ff4d4f;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}
</style>
